package com.xbj.springmvc.core.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xbj.springmvc.core.util.InstallFormUtil;

public class XBJServlet extends HttpServlet{

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.getInitParameter("url-pattern");
		Enumeration<Servlet> ee = this.getServletContext().getServlets();
		while(ee.hasMoreElements()){
			Servlet s = ee.nextElement();
			System.out.println(s);
		}
		// TODO Auto-generated method stub
		// 获取url请求动作（类似add.do）
//		String action = request.getServletPath().substring(1);
		String action = request.getServletPath();
		ServletContext context = this.getServletContext();
		Map<String, String> map = (Map<String, String>) context.getAttribute("springmvc");
		String value = map.get(action);
		String[] values = value.split("\\|\\|");
		String className = values[0];//第一个参数是类名
		String methodName = values[1];//第二个参数是方法
		String[] parasName = values[2].split(",");//第二个参数是方法参数
		Class[] paras = new Class[parasName.length];
		for(int i = 0; i < parasName.length;i++){
			try {
				paras[i] = Class.forName(parasName[i]);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Object myAction;
		Class clazz;
		Object rs = null;
		try {
			clazz = Class.forName(className);
			myAction = clazz.newInstance();
			Method method = clazz.getDeclaredMethod(methodName, paras);//获取方法
			Object[] parasInstaces = new Object[paras.length];
			for (int i = 0; i < paras.length; i++) {
				//装配方法参数
				Object paraInstance = InstallFormUtil.install(paras[i], request);
				parasInstaces[i] = paraInstance;
			}
			//执行方法
			rs = method.invoke(myAction, parasInstaces);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//跳转url
		RequestDispatcher dis = request.getRequestDispatcher(rs.toString());
		dis.forward(request, response);

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}
}
